<?php

namespace app\app\rewrite;

use think\Config;
use think\facade\Cache;
use think\Session;

class Captcha extends  \think\captcha\Captcha
{


    /**
     * 创建验证码
     * @return array
     * @throws Exception
     */
    protected function generate(): array
    {
        $bag = '';

        if ($this->math) {
            $this->useZh  = false;
            $this->length = 5;

            $x   = random_int(10, 30);
            $y   = random_int(1, 9);
            $bag = "{$x} + {$y} = ";
            $key = $x + $y;
            $key .= '';
        } else {
            if ($this->useZh) {
                $characters = preg_split('/(?<!^)(?!$)/u', $this->zhSet);
            } else {
                $characters = str_split($this->codeSet);
            }

            for ($i = 0; $i < $this->length; $i++) {
                $bag .= $characters[rand(0, count($characters) - 1)];
            }

            $key = mb_strtolower($bag, 'UTF-8');
        }

        $hash = password_hash($key, PASSWORD_BCRYPT, ['cost' => 10]);

//        $this->session->set('captcha', [
//            'key' => $hash,
//        ]);

        $token = request()->param('jh_token','');
        Cache::set("captcha-token:{$token}",$hash,60);

        return [
            'value' => $bag,
            'key'   => $hash,
        ];
    }

    /**
     * 验证验证码是否正确
     * @access public
     * @param string $code 用户验证码
     * @return bool 用户验证码是否正确
     */
    public function check(string $code): bool
    {


        $token = request()->param('jh_token','');

        $cache_key="captcha-token:{$token}";

        $key = Cache::get($cache_key);
        if (empty($key)){
            return false;
        }

        $code = mb_strtolower($code, 'UTF-8');

        $res = password_verify($code, $key);

        if ($res) {
            Cache::delete($cache_key);
        }

        return $res;
    }
}